package StudyCode.summary.myfile;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class SerializingObjectsAsXML {
	public static void main(String[] args) {
		MyClass2 settings = new MyClass2("序列化对象为XML");
		try {
			FileSystem fileSystem = FileSystems.getDefault();
			try (FileOutputStream fos = new FileOutputStream("settings.xml"); XMLEncoder encoder = new XMLEncoder(fos)) {
				encoder.setExceptionListener((Exception e) -> {
					System.out.println(e.toString());
				});
				encoder.writeObject(settings);
			}
			try (FileInputStream fis = new FileInputStream("settings.xml");
			     XMLDecoder decoder = new XMLDecoder(fis)) {
				MyClass2 decodedSettings = (MyClass2) decoder.readObject();
				System.out.println("是否相同? " + settings.equals(decodedSettings));
			}

			Path file = fileSystem.getPath("settings.xml");
			List<String> xmlLines = Files
					.readAllLines(file, Charset.defaultCharset());
			xmlLines.stream().forEach((line) -> {
				System.out.println(line);
			});

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class MyClass2 implements Externalizable {
	private String title;

	public MyClass2() {
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeUTF(title);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		title = in.readUTF();
	}

	public MyClass2(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
}
